package org.springblade.common.utils.autoid.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springblade.common.utils.autoid.annotation.AutoIdempotent;
import org.springblade.common.utils.autoid.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author Jackey
 * @date 2021年08月18日 11:32 上午
 */
@Aspect
public class IdempotentAspect {
	@Autowired
	private TokenService tokenService;

	@Pointcut("@annotation(org.springblade.common.utils.autoid.annotation.AutoIdempotent)")
	public void pointCut() {
	}

	@Before("pointCut()")
	public void beforePointCut(JoinPoint joinPoint) throws Exception {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
			.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();

		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		if (!method.isAnnotationPresent(AutoIdempotent.class)) {
			return;
		}

		tokenService.checkToken(request);


	}
}
